package com.lefevre.cms.web.action.theme;

import com.lefevre.cms.bean.RequestResult;
import com.lefevre.cms.bean.ResultCode;
import com.lefevre.cms.bean.theme.Forum;
import com.lefevre.cms.bean.theme.Layout;
import com.lefevre.cms.service.theme.ThemeService;
import com.lefevre.cms.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 显示生成模块引用代码
 */
@Controller
public class ReferenceCodeAction {

    @Resource(name = "themeServiceImpl")
    private ThemeService themeService;

    /**
     * 显示引用代码(目前没用上)
     */
    @ResponseBody
    @RequestMapping("/control/template/referenceCode")
    public String execute(ModelMap model, Integer forumId, String templeteName, String layoutName, Integer returnData) throws Exception {

        Map<String, String> error = new HashMap<>();
        Map<String, Object> returnValue = new HashMap<>();

        if (forumId != null && forumId > 0) {
            Forum forum = themeService.find(Forum.class, forumId);
            if (forum != null) {
                Layout layout = themeService.findLayoutByLayoutId(forum.getLayoutId());
                if (layout != null) {
                    returnValue.put("forum", forum);
                    returnValue.put("layout", layout);

                    //代码
                    if (forum.getInvokeMethod().equals(2)) {
                        String code = forum.getModule().substring(0, StringUtils.lastIndexOfIgnoreCase(forum.getModule(), "_"));//含有后缀
                        returnValue.put("code", code);
                    }
                } else {
                    error.put("layout", "布局不存在");
                }

            } else {
                error.put("forumId", "版块不存在");
            }
        } else {
            error.put("forumId", "版块Id不能为空");
        }
        if (error.size() > 0) {
            return JsonUtils.toJSONString(new RequestResult(ResultCode.FAILURE, error));
        } else {
            return JsonUtils.toJSONString(new RequestResult(ResultCode.SUCCESS, returnValue));
        }
    }
}
